﻿using ContactSMS.Commons.Responses;
using ContactSMS.Domain;
using ContactSMS.Domain.Dto;
using ContactSMS.WebAPI.Controllers.Request;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace ContactSMS.WebAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class UserController : ControllerBase
    {
        private readonly IUserRepository _userRepository;

        public UserController(IUserRepository userRepository)
        {
            this._userRepository = userRepository;
        }

        [HttpGet]
        public async Task<IActionResult> GetUser()
        {
            var user = await this._userRepository.GetUserByTokenAsync();
            ServiceResponse<UserDto> resp = new ServiceResponse<UserDto>();
            var userDto = new UserDto
            {
                Id = user.Id,
                UserName = user.UserName,
                Avatar = user.Avatar,
                CreatTime = user.CreatTime,
                UpdateTime = user.UpdateTime
            };
            resp.Success = true;
            resp.Message = "获取成功";
            resp.Data = userDto;
            return Ok(resp);
        }

        [HttpPost]
        public async Task<IActionResult> ChangePassWordAsync([FromBody] ChangePassWord changePassWord)
        {
            ServiceResponse<bool> resp = new ServiceResponse<bool>();
            if (string.IsNullOrEmpty(changePassWord.PassWord) ||
                string.IsNullOrEmpty(changePassWord.PassWordTwo))
            {
                resp.Success = false;
                resp.Message = "密码不能为空";
                return BadRequest(resp);
            }
            if (!string.Equals(changePassWord.PassWord, changePassWord.PassWordTwo))
            {
                resp.Success = false;
                resp.Message = "两次密码不一样";
                return BadRequest(resp);
            }

            bool res = await this._userRepository.ChangePassWordAsync(changePassWord.PassWord);
            if (res)
            {
                resp.Success = true;
                resp.Message = "修改成功";
                return Ok(resp);
            }

            resp.Success = false;
            resp.Message = "修改失败";
            return BadRequest(resp);
        }


    }
}
